package com.example.video.util.http;

import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;

@Slf4j
@Service
public class HttpUtil {

    @Value("${VideoHandlerServer}")
    private String videoHandlerServer;

    /**
     * 向视频处理服务器发送待翻译视频数据
     * @param id 该视频资源resourceid
     * @param url 视频url
     * @param fromLan 视频语音
     * @param toLan 待翻译语言
     */
    public void sendToVideoServer(String id, String url, String fromLan, String toLan) {
        JSONObject jsonObject = new JSONObject();
        log.info("HttpUtil -> senToVideoServer ->msg: id="+id+", url="+url+", fromLan="+fromLan+", toLan="+toLan);

        // form-data方式传递参数
        MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
        formData.add("id", id);
        formData.add("url", url);
        formData.add("from_lan", fromLan);
        formData.add("to_lan", toLan);
        WebClient client = WebClient.create(videoHandlerServer);
        client.post()
                .uri("/process_video")
                .contentType(MediaType.MULTIPART_FORM_DATA)
                .body(BodyInserters.fromMultipartData(formData))
                .retrieve()
                .bodyToMono(String.class)
                .subscribe(
                        // 处理成功响应
                        response -> log.info("Response from server: " + response),
                        // 处理错误响应
                        error -> System.err.println("Error: " + error.getMessage())
                )
//                .bodyToMono(String.class)
//                .subscribe(response -> log.info("Response from server: " + response))
        ;
    }
}
